//
//  OMHomeViewController.m
//  OMENGO
//
//  Created by 梁尚嘉 on 2017/4/18.
//  Copyright © 2017年 Kamfat. All rights reserved.
//

#import "OMHomeViewController.h"

#import "OMHomeAddressView.h"
#import "OMMallBannerView.h"
#import "OMMallCategoryTableCell.h"
#import "OMHomeSwipeTableCell.h"
#import "OMHomeRecommendTableCell.h"
#import "OMRefreshGifHeader.h"
#import "OMHomeAddressSelectView.h"

#import "OMHomeBannerItem.h"
#import "OMHomeCategory.h"

@interface OMHomeViewController ()<OMHomeAddressSelectViewDelegate,OMSelectionCtrlProtocol,OMHomeAddressViewDelegate>
@property (nonatomic, strong) NSArray <OMHomeBannerItem *>*bannerItems;
@property (nonatomic, strong) NSArray <OMHomeCategory*>*categorys;
@property (nonatomic, strong) NSArray <OMProduct *>*recommends;
@end

@implementation OMHomeViewController

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    SMNotificationPost(SM_NOTIFACATION_NEED_CARTITEM_SHOW, nil);
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.

    [self setupUI];
    [self observeSetup];
    [self getBannersFromWeb];
}


/**
 网络请求重载
 */
- (void)reloadDataFromNetWork
{
    [self getBannersFromWeb];
}

//获取Banner
- (void)getBannersFromWeb
{
    [self startAnimating:YES];
    [KTHttpUtils GET:@"index/ad.jhtml"
          parameters:nil
           needCache:YES
           needToken:NO
            progress:nil
          completion:^(id responseObject, BOOL isSuccess, NSString *message) {
        if (isSuccess) {

            NSString *url = responseObject[OMImagePrefix];
            _bannerItems = [OMHomeBannerItem mj_objectArrayWithKeyValuesArray:responseObject[OMDataKey]];
            NSMutableArray *images = [NSMutableArray arrayWithCapacity:_bannerItems.count];
            for (OMHomeBannerItem *item in _bannerItems) {
                [images addObject:[url stringByAppendingString:item.path]];
            }

            [((OMMallBannerView*)self.tableView.tableHeaderView) configureWithObject:images IsLocal:false];
            [self getHomeCategory];

        }else {
            [OMHUD HUDInfo:message];
            [self showNetWorkError];
            [self.tableView.mj_header endRefreshing];
        }
    }];
}

//获取首页分类
- (void)getHomeCategory
{
    [KTHttpUtils GET:@"index/productCategory.jhtml"
          parameters:nil
           needCache:YES
           needToken:NO
            progress:nil
          completion:^(id responseObject, BOOL isSuccess, NSString *message) {
        [self.tableView.mj_header endRefreshing];
        if (isSuccess) {

            NSArray *categorys = [OMHomeCategory mj_objectArrayWithKeyValuesArray:responseObject[OMDataKey]];
            NSMutableArray *trueCategorys = [NSMutableArray arrayWithCapacity:categorys.count];
            for (OMHomeCategory *category in categorys) {
                category.image = [responseObject[OMImagePrefix] stringByAppendingString:category.image];
                if (category.children.count) {
                    for (OMProduct *product in category.children) {
                        product.image = [responseObject[OMImagePrefix] stringByAppendingString:product.image];
                    }
                    [trueCategorys addObject:category];
                }
            }
            _categorys = trueCategorys;
            [self.tableView reloadData];
            [self getSalesRank];
        }else {
            [self showNetWorkError];
        }
    }];
}


/**
 获取热销排行
 */
- (void)getSalesRank
{
    [self startAnimating:true];
    [KTHttpUtils GET:@"index/hotGoods.jhtml" completion:^(id responseObject, BOOL isSuccess, NSString *message) {
        if (isSuccess) {
            [self startAnimating:false];
            NSArray<OMProduct*>*products = [OMProduct mj_objectArrayWithKeyValuesArray:responseObject[OMDataKey]];
            for (OMProduct *product in products) {
                product.image = [responseObject[OMImagePrefix] stringByAppendingString:product.image?:@""];
            }
            self.recommends = products;
            [self.tableView reloadData];
            [self startAnimating:NO];
        }else {
            [self showNetWorkError];
            [OMHUD HUDInfo:message];
        }
    }];
}


/**
 监听设置
 */
- (void)observeSetup
{
    [SMNotificationMonitorRACSignal(KTOrginalAddressNotificationKey) subscribeNext:^(id x) {
        addressView.address = KTSystemStorageSingleton.originalAddress;
    }];
}


OMHomeAddressView *addressView = nil;
/**
 初始化UI
 */
- (void)setupUI
{
//    self.navigationShadowHidden = YES;

    //消息
    UIBarButtonItem *msgItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"nav_message_25x25_"] style:UIBarButtonItemStylePlain target:nil action:nil];
    msgItem.rac_command = [[RACCommand alloc]initWithSignalBlock:^RACSignal *(id input) {
        if ([Navigator showLoginViewIfUnLogin]) {
            NaviPush(@"OMMessageCenterViewController", nil);
        }
        return [RACSignal empty];
    }];

    //搜索
    UIBarButtonItem *searchItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"nav_search_25x25_"] style:UIBarButtonItemStylePlain target:nil action:nil];
    searchItem.rac_command = [[RACCommand alloc]initWithSignalBlock:^RACSignal *(id input) {
        NaviPush(@"OMGoodSearchViewController", nil);
        return [RACSignal empty];
    }];

    [msgItem setImageInsets:UIEdgeInsetsMake(0, 15, 0, -15)];
    self.navigationItem.rightBarButtonItems = @[
                                                searchItem,
                                                msgItem,
                                                ];

    //地址选择
    self.navigationItem.titleView = [UIView new];
    addressView = [OMHomeAddressView new];
    addressView.addressLabel.text = @"邻檬圈便利仓(嘉信1期店)";
    addressView.frame = CGRectMake(0, 0, 200, SM_SIZE(50));
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:addressView];
    addressView.delegate = self;

    //banner
    OMMallBannerView *banner = [[OMMallBannerView alloc]initWithFrame:CGRectMake(0, 0, SM_SCREEN_WIDTH, /*SM_SCREEN_WIDTH/375*120*/SM_SIZE(350))];
    banner.delegate = self;
    [banner configureWithObject:@[@"home_banner"] IsLocal:YES];
    self.tableView.tableHeaderView = banner;
    self.tableView.sectionHeaderHeight = DBL_EPSILON;

    //footer
    UIView *footer = [UIView new];
    footer.backgroundColor = [UIColor clearColor];
    UIImage *image = [UIImage imageNamed:@"hasNoMore"];
    UIImageView *footerImageV = [[UIImageView alloc]initWithImage:image];
    [footer addSubview:footerImageV];
    footer.frame = CGRectMake(0, 0, 600, image.size.height);
    [footerImageV mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(footer.mas_centerY);
        make.centerX.equalTo(footer.mas_centerX);
    }];
    _tableView.tableFooterView = footer;

    @weakify(self);
    self.tableView.mj_header = [OMRefreshGifHeader headerWithRefreshingBlock:^{
        @strongify(self);
        [self getBannersFromWeb];
    }];
}

#pragma mark - OMSelectionCtrlProtocol
- (void)didSelectObjectAtIndex:(NSUInteger)index
{
    NSString *url = [_bannerItems[index] url];
#ifdef DEBUG
    url = @"http://192.168.25.7/test.html";
#endif
    if ([url isUrl]) {
        NaviPush(@"OMAdvertisementViewController", @{@"url":url});
    }
}


#pragma mark - tableView delegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 3;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 1) {
        return self.categorys.count;
    }
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        return [OMMallCategoryTableCell tableViewCellWithTableView:tableView];
    }
    else if (indexPath.section == 1)
    {
        OMHomeSwipeTableCell *cell = [OMHomeSwipeTableCell tableViewCellWithTableView:tableView];
        [cell configureCellWithObj:self.categorys[indexPath.row]];
        return cell;
    }
    else if (indexPath.section == 2)
    {
        OMHomeRecommendTableCell *cell = [OMHomeRecommendTableCell tableViewCellWithTableView:tableView];
        [cell configureCellWithObj:self.recommends];
        return cell;
    }
    return nil;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        return [OMMallCategoryTableCell cellHeight];
    }else if (indexPath.section == 1) {
        return [OMHomeSwipeTableCell cellHeight];
    }else if (indexPath.section == 2) {
        return [OMHomeRecommendTableCell cellHeightWithItems:self.recommends];
    }
    return [OMMallCategoryTableCell cellHeight];
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return DBL_EPSILON;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return DBL_EPSILON;
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    if (selectView) {
        [selectView dismiss];
    }
}


#pragma mark - OMHomeAddressViewDelegate
OMHomeAddressSelectView *selectView = nil;
- (void)didClickAddressView
{
    if (!addressView.selected) {
        [selectView dismiss];
    }else {
        selectView = [OMHomeAddressSelectView new];
        selectView.frame = CGRectMake(0, CGRectGetMaxY(self.navigationBar.frame), SM_SCREEN_WIDTH, SM_SCREEN_HEIGHT-64-49);
        selectView.delegate = self;
        [selectView showInView:self.view];
    }
}

#pragma mark - OMHomeAddressSelectViewDelegate
- (void)didDismiss
{
    selectView = nil;
    addressView.selected = false;
}

- (void)didSelectItem:(id)item AtIndex:(NSUInteger)index
{
    [OMFakeAction fakeLoadDataActionWithController:self];
}
@end
